import { createStore } from 'vuex'
import { getMenus } from '@/api/menus.js'
import { user, userCheck } from '@/api/user.js'
import { adUser } from '@/store/ad_user.js'
import { adImg } from '@/store/ad_img.js'
import { adNews } from '@/store/ad_news.js'
import { adArticle } from '@/store/ad_article'
import { adSupply } from '@/store/ad_supply'
import { adDemand } from '@/store/ad_demand'


export default createStore({
  state: {
    menus: [
      {title: "首页", is_sub: 0, index: "1"}
    ],
    isLogin: false,
    user: {
      role: -1
    },
  },
  mutations: {
    async setMenus (state, role) {
      let data = await getMenus(role);
      state.menus = data;
    },
    async storeCheckLoginStatus(state){
      let data = await userCheck.checkUserStatus();
      console.log('data', data)
      state.isLogin = data.status;
      state.user = data.user;
      if(state.isLogin){
        this.commit('setMenus', data.user.role)
      }
    },
    storeLogout(state){
      user.logout();
      state.isLogin = false;
      state.menus = [
        {title: "首页", is_sub: 0, index: "1"}
      ];
      state.user = {}
    },
    storeSetUser(state, user){
      state.user = user;
    }
  },
  actions: {
    async storeCheckLoginStatusAction({ commit,state }){
      let data = await userCheck.checkUserStatus();
      state.isLogin = data.status;
      state.user = data.user;
      if(state.isLogin){
        commit('setMenus', data.user.role)
      }
      return new Promise ((resolve, reject) => {
        if (state.user.role != -1){
          resolve()
        }else{
          reject()
        }
      })
      
    }
  },
  modules: {
    au: adUser,
    ai: adImg,
    an: adNews,
    aa: adArticle,
    as: adSupply,
    ad: adDemand,
  }
})
